import React, { useRef, useState } from 'react';
import { Modal, Form, Input, Switch, message, Space, Tag, AutoComplete } from 'antd';
import "./index.less";
import { addAllElement, addMenuElement, delMenu, delMenuElement, editMenu, getMenuElement, getTypeList, getMenuList, toggleElement, updateMenuElement, upload } from '@/services/demo/UserController';
import { ActionType, ProTable } from '@ant-design/pro-components';
import { PageCode, MenuCode } from "@/../../code";
import { useModel } from '@umijs/max';
import AuthButton from "@/components/AuthButton";
type Props = {
  menuId?: string;
  nodeInfo: { root?: Boolean, name?: string, code?: string; trunk?: boolean; }
}

const App: React.FC<Props> = ({ menuId, nodeInfo }) => {
  const [model, contextHolder] = Modal.useModal();
  const tableRef = useRef<ActionType>();
  const [authForm] = Form.useForm();
  const [isOpenElement, setIsOpenElement] = useState(false);
  const [authOpen, setAuthOpen] = useState(false);
  const [authModalType, setAuthModalType] = useState("新增");
  const [initialAuthValues, setInitialAuthValues] = useState({ status: 1, code: "", isHiden: 0 });
  const { initialState: { elements } } = useModel('@@initialState') as any;
  const [selectOptions, setSelectOptions] = useState<{ label: string, value: string; }[]>();
  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '类型',
      dataIndex: 'type',
      render: (type: string) => {
        const text = type == "10" ? "按钮" : type == "20" ? "链接" : "其他";
        return <Tag>{text}</Tag>;
      },
      search: false,
    },
    {
      title: '编码',
      dataIndex: 'code',
      search: false,
    },
    {
      title: '名称',
      dataIndex: 'name'
    },
    {
      title: '描述',
      dataIndex: 'description',
      search: false,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      search: false,
    },
    {
      title: '启用',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        1: { text: '启用' },
        0: { text: '未启用' },
      },
      render: (text: number, row: { id: string; }) => <Switch disabled={!elements.includes(MenuCode['BTN_AUTH_STATUS'])} defaultChecked={Boolean(text)} onChange={() => toggleElement(row.id)} />
    },
    {
      title: '更新时间',
      dataIndex: 'updateAt',
      search: false,
      valueType: "dateTime"
    },

    {
      title: '操作',
      fixed: 'right',
      search: false,
      width: 120,
      render: (user: API.UpdateMenuElement) => {

        return [
          <AuthButton key="edit" size='small' type='link' permission={MenuCode['BTN_EDIT_AUTH']} onClick={() => handleEdit(user)}>编辑</AuthButton>,
          <AuthButton key="delete" size='small' type='link' danger permission={MenuCode['BTN_DEL_AUTH']} onClick={() => handleDelete(Number(user.id))}>删除</AuthButton>
        ];
      },
    },
  ];


  const addAll = async () => {
    const confirmed = await model.confirm({ content: "确定为所有元素授权（只有存在于编码列表才会生效）?" });
    if (confirmed) {
      const filterOptions = selectOptions?.filter((option: any) => !option.disabled);
      if (filterOptions?.length) {

        const options: any = filterOptions?.map((option: any) => ({ code: option.value, description: option.label, menuId, name: option.label, status: 1, isHiden: 0 }));
        addAllElement(options).then(res => {
          if (res.success) {
            message.success("新增授权元素成功");
            tableRef.current?.reload();
          }
        });
      } else {
        message.warning("无效操作");
      }
    }
  };
  const onCodeChange = (value: string, option: any) => {
    console.log(value, option);
    if (JSON.stringify(option) !== "{}") {
      authForm.setFieldValue("code", option.value);
      authForm.setFieldValue("name", option.label);
      authForm.setFieldValue("description", option.label);
    }
  };
  const handleEdit = (user: API.UpdateMenuElement) => {
    setAuthModalType("编辑");
    setAuthOpen(true);
    authForm.setFieldsValue(user);

  };
  const handleDelete = async (id: number) => {
    const confirmed = await model.confirm({ content: "确定删除?" });
    if (confirmed) {
      delMenuElement(id).then(res => {
        if (res.success) {
          message.success("删除成功");
          tableRef.current?.reload();
        }
      });
    }
  };

  const openElementModal = () => {
    setIsOpenElement(true);
    tableRef.current?.reset?.();
  };

  const onAuthFinish = (value: API.UpdateMenuElement) => {
    console.log('表单提交', value);
    if (authModalType === "新增") {
      Object.assign(value, { menuId });
      addMenuElement(value).then(res => {
        if (res.success) {
          message.success("新增授权元素成功");
          tableRef.current?.reload();
          setAuthOpen(false);
        }
      });
    } else {
      updateMenuElement(value).then(res => {
        if (res.success) {
          message.success("更新授权元素成功");
          tableRef.current?.reload();
          setAuthOpen(false);
        }
      });
    }
  };
  const addAuth = () => {
    setAuthOpen(true);
    setAuthModalType("新增");
    // 、、、、、、、、、、、、、、、、、、、、、、、、、、新增的时候这里吧id去除了导致授权按钮点击没id了
    authForm.resetFields();
  };

  const onAuthOpen = (value: boolean) => {
    authForm.setFieldValue("status", Number(value));
  };
  const onAuthShow = (value: boolean) => {
    authForm.setFieldValue("isHiden", Number(value));
  };

  return (
    <>
      <AuthButton permission={MenuCode['BTN_AUTH']} onClick={openElementModal}>按钮授权</AuthButton>

      <Modal okText="提交" title={nodeInfo.name + " - 页面元素"} width={1200} maskClosable={false} open={isOpenElement} onCancel={() => setIsOpenElement(false)} footer={false}>
        <ProTable
          cardBordered
          actionRef={tableRef}
          params={{ menuId }}
          request={async (params) => {
            const { current, pageSize, menuId, name, status } = params as any;
            const { success, result: { datas, total } } = await getMenuElement({ page: current!, size: pageSize!, param: { menuId, status, name } });

            const options = (PageCode as any)[nodeInfo.code!.slice(0, -1)];
            options?.map((option: any) => (option.disabled = datas.find((data: { code: string; }) => data.code == option.value)));
            setSelectOptions(options);

            return { data: datas, total, success };

          }}
          columns={columns}
          rowKey="id"
          headerTitle={<Space><AuthButton permission={MenuCode['BTN_ADD_AUTH']} type='primary' onClick={addAuth}>新增</AuthButton><AuthButton permission={MenuCode['BTN_ADD_ALL_AUTH']} type='primary' onClick={addAll}>一键新增</AuthButton></Space>}
        />
      </Modal>

      <Modal width="400px" title={authModalType + "权限按钮"} maskClosable={false} open={authOpen} onOk={() => authForm.submit()} onCancel={() => setAuthOpen(false)} okText="提交"  >
        <Form size='large' form={authForm} initialValues={initialAuthValues} onFinish={onAuthFinish}>
          <Form.Item
            name="id"
            hidden
          >
            <Input />
          </Form.Item>

          {nodeInfo.code && <Form.Item
            label="编码"
            name="code"
            rules={[{ required: true, message: '请输入编码' }]}
          >
            <AutoComplete
              placeholder="请选择编码"
              onChange={onCodeChange}
              allowClear
              options={selectOptions}
            />
          </Form.Item>}
          <Form.Item label="名称"
            name="name"
            rules={[{ required: true, message: '请输入名称' }]}>
            <Input allowClear placeholder='请输入名称' maxLength={30} showCount />
          </Form.Item>

          {/* <Form.Item noStyle dependencies={["type"]}>
            {({ getFieldValue }) => getFieldValue('type') === '20' && <Form.Item
              label="链接"
              name="href"
              rules={[{ required: true, message: '请输入链接' },]}
            >
              <Input allowClear placeholder='请输入链接' />
            </Form.Item>}
          </Form.Item> */}

          <Form.Item
            label="描述"
            name="description"
          >
            <Input.TextArea placeholder='请输入描述' allowClear autoSize={{ minRows: 3 }} showCount maxLength={500} />
          </Form.Item>
          <Form.Item
            label="启用"
            name="status"
          >
            <Switch onChange={onAuthOpen} />
          </Form.Item>
          <Form.Item
            label="隐藏"
            name="isHide"
          >
            <Switch onChange={onAuthShow} />
          </Form.Item>
        </Form>
      </Modal>

      {contextHolder}
    </ >
  );
};

export default App;